package br.uff.gdse.positionevaluation.evaluators;

import java.util.ArrayList;
import java.util.List;

import br.uff.gdse.positionevaluation.entity.Result;
import br.uff.gdse.positionevaluation.queries.XMLQuery;

public class XMLDBEvaluator {

	private IDBInterface dbInterface;
	
	private static final int COUNT_EVALUATED_QUERIES = 20;
	
	public XMLDBEvaluator(IDBInterface dbInterface) {
		this.dbInterface = dbInterface;
	}
	
	public List<Result> evaluate(XMLQuery query){
		
		int[] positionValues = getPositionValues(query);
		List<Result> results = new ArrayList<Result>();
		
		for (int i = 0; i < positionValues.length; i++) {
			String positionQuery = query.getQuery()+"[position()=" + positionValues[i] + "]";
			XMLQuery xmlPositionQuery = new XMLQuery(query.getCollection(), positionQuery);
			
			double[] responseTimes = new double[10];
			for (int j = 0; j < responseTimes.length; j++) {
				long initialTime = System.currentTimeMillis();
				dbInterface.executeQuery(xmlPositionQuery).get(0);
				long elapsedTime = System.currentTimeMillis() - initialTime;
				System.out.println(elapsedTime);
				responseTimes[j] = elapsedTime;
			}
			Result result = new Result(responseTimes, xmlPositionQuery);
			results.add(result);
		}
		
		return results;
		
	}

	private int[] getPositionValues(XMLQuery query) {
		String countQuery = "count(" + query.getQuery() + ")";
		XMLQuery xmlCountQuery = new XMLQuery(query.getCollection(), countQuery);
		
		List<Object> result = dbInterface.executeQuery(xmlCountQuery);
		int[] positions;
		int count = Integer.parseInt(result.get(0).toString());
		if(count>COUNT_EVALUATED_QUERIES){
			positions = new int[COUNT_EVALUATED_QUERIES];
			int intervalo = count / COUNT_EVALUATED_QUERIES;
			for (int i = 0; i < positions.length; i++) {
				positions[i] = intervalo*i+1;
			}
		}else{
			positions = new int[count];
			for (int i = 0; i < positions.length; i++) {
				positions[i] = i+1;
			}
		}
		return positions;
	}
}
